<?php
function sess(){
    if (! session('uid')||!session('username')) {
        redirect(U('Index/index'));
    }
}
function control(){
    $map['role'] = session('depname');
    $list = M('Group')->join('crm_group_url on crm_group.id = crm_group_url.group_id')
    ->join('crm_url on crm_group_url.url_id = crm_url.id')->where($map)->field('url')
    ->select();
    return $list;
}

function login($admin)
{
    $MU = M('user');
    $account = $MU->getByUsername($admin['username']);
    if (! $account) {
        return array(
            'status' => false,
            'data' => '用户不存在！'
        );
        die();
    }
    
    if ($account['password'] != encrypt($admin['password'])) {
        return array(
            'status' => false,
            'data' => '密码不正确！'
        );
        die();
    }
    
    session('uid', $account['id']);
    session('username', $account['username']);
    session("truename", $account['truename']);
    session('depname', $account['depname']);
    session('posname', $account['posname']);
    session('loginip', get_client_ip());
    session('logintime', date("Y-m-d H:i:s", time()));
    session('logins', $account['logins']);
    
    $data['id'] = session('uid');
    $data['logintime'] = date("Y-m-d H:i:s", time());
    $data['loginip'] = get_client_ip();
    $data['logins'] = array(
        'exp',
        'logins+1'
    );
    $data['update_time'] = time();
    M("user")->save($data);
    
    $dat['username'] = session('username');
    $dat['content'] = '登录成功！';
    $dat['os'] = $_SERVER['HTTP_USER_AGENT'];
    $dat['url'] = U();
    $dat['addtime'] = date("Y-m-d H:i:s", time());
    $dat['ip'] = get_client_ip();
    M("log")->add($dat);
    
    return array(
        'status' => true
    );
}

function logout()
{
    $dat['username'] = session('username');
    $dat['content'] = '退出成功！';
    $dat['os'] = $_SERVER['HTTP_USER_AGENT'];
    $dat['url'] = U();
    $dat['addtime'] = date("Y-m-d H:i:s", time());
    $dat['ip'] = get_client_ip();
    M("log")->add($dat);
    session_unset();
    session_destroy();
}

// 数据处理
function encrypt($data)
{
    return md5(md5($data));
}

// 更新操作时间
function updateTime()
{
    $data['id'] = session('uid');
    $data['loginip'] = get_client_ip();
    $data['update_time'] = time();
    M("user")->save($data);
}

function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        
        if ($suffix) {
            
            return mb_substr($str, $start, $length, $charset) . "...";
        } else {
            
            return mb_substr($str, $start, $length, $charset);
        }
    } elseif (function_exists('iconv_substr')) {
        
        if ($suffix) {
            
            return iconv_substr($str, $start, $length, $charset) . "...";
        } else {
            
            return iconv_substr($str, $start, $length, $charset);
        }
    }
    
    $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    
    $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    
    $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    
    preg_match_all($re[$charset], $str, $match);
    
    $slice = join("", array_slice($match[0], $start, $length));
    
    if ($suffix) {
        
        return $slice . "...";
    } else {
        
        return $slice;
    }
}

function getpage($count, $pagesize = 10)
{
    $p = new Think\Page($count, $pagesize);
    $p->setConfig('header', '&nbsp;&nbsp;共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页');
    $p->setConfig('prev', '上一页');
    $p->setConfig('next', '下一页');
    $p->setConfig('last', '末页');
    $p->setConfig('first', '首页');
    $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
    $p->lastSuffix = false; // 最后一页不显示为总页数
    return $p;
}

function xlsout($fileName = '数据表', $headArr, $list)
{
    import("Org.Util.PHPExcel");
    import("Org.Util.PHPExcel.Writer.Excel5");
    import("Org.Util.PHPExcel.IOFactory.php");
    // 对数据进行检验
    if (empty($list) || ! is_array($list)) {
        die("data must be a array");
    }
    // 检查文件名
    if (empty($fileName)) {
        exit();
    }
    
    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";
    
    // 创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    
    // 设置表头
    $key = ord("A");
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    
    // 设置为文本格式
    foreach ($list as $key => $rows) { // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入
            $j = chr($span);
            
            $objActSheet->setCellValueExplicit($j . $column, $value);
            $span ++;
        }
        $column ++;
    }
    
    $fileName = iconv("utf-8", "gb2312", $fileName);
    // 重命名表
    // $objPHPExcel->getActiveSheet()->setTitle('test');
    // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean(); // 清除缓冲区,避免乱码
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}

function _search($dbname = '')
{
    $keys = trim(I('post.keys'));
    $model = D($dbname);
    $map = array();
    foreach ($model->getDbFields() as $key => $val) {
        if (isset($keys) && $keys != '') {
            $map[$val] = array(
                'like',
                '%' . $keys . '%'
            );
        }
    }
    $map['_logic'] = 'or';
    if (isset($keys) && $keys != '') {
        $where['_complex'] = $map;
        return $where;
    } else {
        return $map;
    }
}

function add($dbname = '')
{
    $model = D($dbname);
    $data = I('post.');
    if (false === $data = $model->create()) {
       header('Refresh:2;url=/');
		die('失败，请检查值是否已经存在');
    }
    if ($model->add($data)) {
        return true;
    } else {
        return false;
    }
}

function edit($dbname = '')
{
    $model = D($dbname);
    $data = I('post.');
    if (false === $data = $model->create()) {
        header('Refresh:2;url=/');
		die('失败，请检查值是否已经存在');
        //$this->error('失败，请检查值是否已经存在');
    }
    if ($model->save($data)) {
        return true;
    } else {
        return false;
    }
}

function del($dbname = '')
{
    $model = D($dbname);
    $id = I('get.id');
    if ($model->delete($id)) {
        return true;
    } else {
        return false;
    }
}

//验证方法
function getuserid(){
	return session("uid");
}


function gettruename(){
	return session("truename");
}

function gettime(){
	return date('Y-m-d H:i:s',time());
}